package com.qty.apkviewer.hub

import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.Window
import androidx.appcompat.app.AlertDialog
import com.qty.apkviewer.R
import com.qty.apkviewer.utils.Utils

class QProgressHub private constructor() {

    private var activity: Activity? = null
    private var progressDialog: AlertDialog? = null

    fun show() {
        activity?.let {
            val isShowing = progressDialog?.isShowing ?: false
            if (!isShowing) {
                progressDialog = AlertDialog.Builder(it)
                    .setView(LayoutInflater.from(it).inflate(R.layout.progress_hub, null))
                    .setCancelable(false)
                    .create()
                progressDialog?.let {dialog ->
                    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
                    dialog.window?.let { window ->
                        window.setDimAmount(0.5f)
                        window.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
                        window.decorView.setBackgroundColor(Color.TRANSPARENT)
                        window.attributes.let { params ->
                            params.y = Utils.dpToPx(it, 72)
                            params.width = Utils.dpToPx(it, 128)
                            params.height = Utils.dpToPx(it, 128)
                        }
                    }
                    dialog.show()
                }
            }
        }
    }

    fun hide() {
        progressDialog?.let {
            if (it.isShowing) {
                it.cancel()
            }
        }
    }

    companion object {

        private val sInstance: QProgressHub = QProgressHub()
        fun getInstance(activity: Activity): QProgressHub {
            sInstance.activity = activity
            return sInstance
        }
    }
}